package com.gitee.dupe.common.captcha;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.core.img.GraphicsUtil;
import cn.hutool.core.util.ObjectUtil;

import java.awt.*;
import java.awt.image.BufferedImage;

public class TransparentCaptcha extends AbstractCaptcha {


    public TransparentCaptcha(int width, int height, int codeCount) {
        super(width, height, codeCount, 0);
    }

    @Override
    public Image createImage(String code) {
        BufferedImage image = new BufferedImage(this.width, this.height, 1);
        Graphics2D g = GraphicsUtil.createGraphics(image, (Color) ObjectUtil.defaultIfNull(this.background, Color.WHITE));
        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        g = image.createGraphics();
        this.drawString(g, code);
        return image;
    }

    private void drawString(Graphics2D g, String code) {
        if (null != this.textAlpha) {
            g.setComposite(this.textAlpha);
        }

        GraphicsUtil.drawStringColourful(g, code, this.font, this.width, this.height);
    }

}
